<?php

namespace app\models;

use think\Db;
use think\Model;
use EasyWeChat\Factory;


class Message extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $defaultSoftDelete = 0;

    /**
     * 资产变动变更记录
     * $type = 1 入账 2提现
     * @return void
     */
    public static function MessageInsert($orderid = 0, $user_id = 0, $ouser_id = 0, $status = 0, $endstatus = 0, $text = 0)
    {
        $res2 = (new Message())->save([
            'orderid' => $orderid,
            'user_id' => $user_id,
            'ouser_id' => $ouser_id,
            'status' => $status,
            'endstatus' => $endstatus,
            'text' => $text,
        ]);
        if (!$res2) {
            throw new \Exception("通知记录失败", 100);
        }
    }


    //公众号通知提醒
    public function Message($openid = '', $template_id = '', $data = [], $appid, $pagepath, $url = '')
    {
        $config = config('wechat2.');
        $app = Factory::officialAccount($config);
        $send_data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的 openid
            'url' => $url,
            'data' => $data
        ];
        if (empty($url)) {
            $send_data['miniprogram'] = [
                'appid' => $appid,
                'pagepath' => $pagepath,
            ];
        }
        $result = $app->template_message->send($send_data);
        return $result;
    }

    //小程序订单变更通知提醒
    public function MessageOrder($openid = '', $template_id = '', $data = [], $pagepath)
    {
        $config = config('wechat.');
        $app = Factory::officialAccount($config);
        $send_data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的 openid
            'page' => $pagepath,
            'data' => $data
        ];
        $result = $app->template_message->sendMessageSubscribe($send_data);
        return $result;
    }
}
